<?php

namespace App\Http\Controllers\Api\CMS;

use App\Models\CMS\Content;
use App\Models\CMS\Blog;
use App\Http\Resources\ContentBlogResource;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Services\CmsService;
use Illuminate\Support\Facades\DB;

class ContentBlogController extends Controller
{
    /**
     * 构造方法
     * @var CmsService
     */
    public $cmsService;

    public function __construct()
    {
        $this->cmsService = new CmsService();
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection
     */
    public function index(Request $request)
    {
        $keyword = $request->get('keyword', '');
        $category_id = $request->get('category_id', []);
        $models = Blog::query()->when($category_id, function ($query) use ($category_id) {
            return $query->whereHas('contents.categorylabel', function ($q) use ($category_id) {
                foreach ($category_id as $item) {
                    $q->where('category_path', 'like', "%{$item}%");
                }
            });
        })->when($keyword, function ($query) use ($keyword) {
            $query->where('content', 'like', '%' . $keyword . '%')
                ->whereHas('contents', function ($q) use ($keyword) {
                    $q->where('title', 'like', '%' . $keyword . '%');
                });
        })
            ->with('contents.category', 'contents.categorylabel')
            ->orderByDesc('cms_content_blogs.id')->paginate();
        return ContentBlogResource::collection($models);
    }

    /**
     * 按钮状态更改
     * @param $cbId
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeButton($cbId)
    {
        $blogModel = Blog::query()->where('id', $cbId)->first();
        $model = $blogModel->contents;
        $status = $model->status;
        if ($status == 0) {
            $model->status = 1;
        } else {
            $model->status = 0;
        }
        if ($model->save()) {
            return response()->json('状态修改成功');
        } else {
            return response()->json('状态修改失败', 422);
        }

    }

    /**
     * @param Request $request
     * @return ContentBlogResource|\Illuminate\Http\JsonResponse
     */
    public function store(Request $request)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            $columns = $this->syncColumns($data['category']);
            $content = new Content();
            $content->fill($data);
            $content->content_detail_type = 'ContentBlog';
            $content->content_detail_id = 0;
            $content->status = 1;
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->view_count = $content->view_count ? $content->view_count : 0;
            $content->save();
            $Blog = new  Blog();
            $Blog->fill($data);
            $Blog->content_id = $content->id;
            $Blog->save();
            $content->content_detail_id = $Blog->id;
            $content->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentBlogResource($Blog);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }

//        return new BlogResource($Blog);

    }

    /**
     * 此方法用于将content表的id传给Blog表的content_id字段
     * @param $contentId
     * @return mixed
     */
    public function updateContentById($contentId)
    {
        $Blog = $this->findModel($contentId);
        $BlogId = $Blog->id;
        return $BlogId;
    }

    /**
     * @param $cbId
     * @return ContentBlogResource
     */
    public function show($cbId)
    {
        $model = $this->findModel($cbId);
        return new ContentBlogResource($model);
    }

    /**
     * @param Request $request
     * @param $cbId
     * @return ContentBlogResource|\Illuminate\Http\JsonResponse
     */
    public function update(Request $request, $cbId)
    {
        DB::beginTransaction();
        try {
            $data = $request->all();
            $columns = $this->syncColumns($data['category']);
            $Blog = $this->findModel($cbId);
            $content = $Blog->contents;
            $content->fill($data);
            $tags = $data['tags'];
            $this->cmsService->asyncTags($tags);
            $content->tags = json_encode($tags);
            $content->save();
            $Blog->fill($data);
            $Blog->save();
            $content->save();
            $content->category()->sync($columns);
            DB::commit();
            return new ContentBlogResource($Blog);
        } catch (\Exception $e) {
            DB::rollBack();
            return response()->json($e->getMessage(), 422);
        }
    }

    /**
     * 格式化栏目参数
     * @param $column
     * @return array
     */
    protected function syncColumns($column)
    {
        $arr = [];
        foreach ($column as $item) {
            if ($item) {
                $arr[end($item)] = ['category_path' => '-' . implode("-", $item) . '-'];
            }
        }
        return $arr;
    }

    /**
     * @param $cbId
     * @return \Illuminate\Database\Eloquent\Model
     */
    protected function findModel($cbId)
    {
        $model = Blog::query()->findOrFail($cbId);
        return $model;
    }

    /**
     * @param $cbId
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function destroy($cbId)
    {
        $Blog = $this->findModel($cbId);
        $content = $Blog->contents;
        $content->delete();
        $Blog->delete();
        if ($Blog->delete()) {
            return response()->json(['删除成功！']);
        } else {
            return response()->json(['没有删除成功！'], 422);
        }
    }
}
